﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LDSP.BRL;
using BYFW.DAL;
using System.Data;
using LDSP.Helper;
using BLL.Util;
using BYFW.SFL;
using System.IO;
using LDSP.Util.Mail;

namespace LDSP.UI.Admin
{
    public partial class EmailSender1 : LDSP.BRL.BaseSysAdminPage
    {
        private MailInfo _mailInfo;

        private string SelectedIds
        {
            get { return Request.Params["MailCodification"]; }
        }

        private MailType Type
        {
            get
            {
                MailType t = MailType.Codification;
                string type = Request.Params["type"] != null ? Request.Params["type"].ToString() : string.Empty;
                if (type.Equals("News"))
                {
                    t = MailType.News;
                }

                return t;
            }
        }

        //根据数据类型选择op；highlight关键的字
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (this.RB())
                {
                    this.InitDataDynamicBefore();
                    if (!IsPostBack)
                    {
                        this.InitData();
                        this.BindGrid();
                    }
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        /// <summary>
        /// 打开页面时进行判断是否有权限并跳转
        /// </summary>
        /// <returns></returns>
        protected bool RB()
        {
            return this.AllowSystemUser();
        }

        protected void AddFilterFields()
        {
            for (int i = 0; i < g_pageInfo.FldList.Count; i++)
            {
                g_pageInfo.FldList[i].Items.Clear();
            }
            g_pageInfo.AddFilterField("公司名", "code", EDataType.String, false, null);
            g_pageInfo.AddFilterField("显示名称", "name", EDataType.String, false, null);
            g_pageInfo.AddFilterField("备注", "comment", EDataType.String, false, null);
        }
        /// <summary>
        /// 传入参数，设置过滤条件
        /// </summary>
        protected void SetSpecialPageInfo()
        {
            g_pageInfo.Direction = true;
            g_pageInfo.Sort = "code";
            g_pageInfo.PageSize = this.GetInt(this.ddl_pageSize.SelectedValue);
            g_pageInfo.PageIndex = this.grd_list.PageIndex;
            if (needCachePageInfo)
            {
                //此处可恢复缓存的数据
            }
        }
        protected void CachePageInfo()
        {
            if (needCachePageInfo)
            {
                //缓存页面信息
                g_pageInfo.CachePageFilterControlInfo();
                //此处添加其他需要缓存的信息
            }
        }
        protected void BindDDLPageSize()
        {
            CommonControlInitial.InitialPageSize(this.ddl_pageSize);
        }

        protected void InitData()
        {
            this.BindDDLPageSize();
            //初始化页面过滤控件的显示内容
            g_pageInfo.InitFilterControls();
            //加入页面特有的过滤字段
            this.AddFilterFields();
            //不缓存则清空页面信息
            if (!needCachePageInfo)
            {
                g_pageInfo.ClearPageInfo();
            }
            //设定初始的过滤条件：有传入时或缓存PageInfo时
            this.SetSpecialPageInfo();

            this.BindDDLIndustry();

            InitMailContent();
            g_pageInfo.InitPageFilterControlByPageInfo();
            //生成条件表达式
            g_pageInfo.GetCondition();

            this.ddl_pageSize.SelectedValue = g_pageInfo.PageSize.ToString();

        }

        private void InitMailContent()
        {
            this.txt_Title.Text = _mailInfo.Subject;
            this.txt_Content.Text = _mailInfo.Content;
            this.txt_Attachment.Text = _mailInfo.Attachments;
        }

        protected void BindDDLIndustry()
        {
            DataTable dt = new Industry().GetAll();
            this.ddl_industry.Items.Clear();
            this.ddl_industry.Items.Add(new ListItem("--请选择行业--", "0"));
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                this.ddl_industry.Items.Add(new ListItem(dt.Rows[i]["name"].ToString(), dt.Rows[i]["id"].ToString()));
            }
            try
            {
                this.ddl_industry.SelectedIndex = 0;
            }
            catch { }
        }
        protected void InitDataDynamicBefore()
        {
            _mailInfo = MailInfoFactory.GetMailInfo(Type, SelectedIds);
            _mailInfo.InitMailContent();

            this.JSInitFilterControls();
        }
        protected void BindGrid()
        {
            DataTable dt = CommonOP.SortedTable(new Enterprise().GetRecords(g_pageInfo.ConditionWhere, true), g_pageInfo.GetSortExpression());

            this.grd_list.PageSize = g_pageInfo.PageSize;
            this.grd_list.PageIndex = g_pageInfo.PageIndex;
            this.grd_list.DataSource = dt;
            this.grd_list.DataBind();
            this.CachePageInfo();

            this.TotalRecords.Text = LDSP.Helper.StringUtil.GetSearchText(dt.Rows.Count);
        }

        protected void GetCondition()
        {
            string cond = "";
            if (this.txt_code.Text.Trim() != "")
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLMultiCondition("code", EDataType.String, this.txt_code.Text.Trim(), true, true), true);
            }
            if (this.ddl_industry.SelectedIndex > 0)
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("industryID", EDataType.Int, this.ddl_industry.SelectedValue, "=", true), true);
            }
            if (this.txt_address.Text.Trim() != "")
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLMultiCondition("address", EDataType.String, this.txt_address.Text.Trim(), true, true), true);
            }
            g_pageInfo.Condition = cond;
        }

        protected void btn_search_Click(object sender, EventArgs e)
        {
            try
            {
                this.GetCondition();
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        protected void grd_list_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                int id = this.GetInt(e.CommandArgument.ToString());
                if (id == 0)
                {
                    return;
                }
                if (e.CommandName == "updateItem")
                {
                    this.JSRedirect("AddEnterprise.aspx?id=" + id, false);
                }
                if (e.CommandName == "deleteItem")
                {
                    Enterprise ett = new Enterprise();
                    ett.GetProperties(id);
                    ett.Delete();
                }
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void grd_list_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    Enterprise ett = new Enterprise();
                    ett.GetProperties(((DataRowView)e.Row.DataItem).Row);
                    this.ShowSequenceNumber(e.Row, 1);
                    e.Row.Cells[2].Text = ett.Industry.Name;

                    CheckBox chb = (CheckBox)e.Row.FindControl("chb");
                    chb.Attributes["docid"] = ett.ID.ToString();
                    if (this.MultiPageIncludeCheckedId(this.hid_docIDs, ett.ID))
                    {
                        chb.Checked = true;
                    }
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void grd_list_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                g_pageInfo.PageIndex = e.NewPageIndex;
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void grd_list_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                if (g_pageInfo.Sort == e.SortExpression)
                {
                    g_pageInfo.Direction = !g_pageInfo.Direction;
                }
                else
                {
                    g_pageInfo.Direction = true;
                }
                g_pageInfo.Sort = e.SortExpression;
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void ddl_pageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                g_pageInfo.PageSize = this.GetInt(this.ddl_pageSize.SelectedValue);
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        protected void btn_Send_Click(object sender, EventArgs e)
        {
            EnablePage(false);

            IList<string> toList = new List<string>();
            IList<string> fileList = new List<string>();

            //获取邮件接收方地址。
            List<int> ids = this.GetAllCheckedItems(this.hid_docIDs);
            for (int i = 0; i < ids.Count; i++)
            {
                Enterprise ett = new Enterprise();
                ett.GetProperties(ids[i]);

                if (!string.IsNullOrEmpty(ett.Email))
                {
                    string[] mails = ett.Email.Split(';');
                    foreach (string mail in mails)
                    {
                        string[] emails = mail.Split('；');
                        foreach (string email in emails)
                        {
                            toList.Add(email);
                        }
                    }
                }
            }

            //获取附件。
            if (this.chkIncludeFile.Checked)
            {
                fileList = _mailInfo.GetAttachmentList(Server);
            }

            //获取附件名称
            IList<string> attachNames = this.txt_Attachment.Text.Replace('；', ';').Split(';').ToList<string>();

            //发送邮件。
            try
            {
                MailSender.SendMail(
                    toList,
                    this.txt_Title.Text,
                    this.txt_Content.Text,
                    attachNames,
                    fileList);

                this.JSAlert("邮件已发送完毕!");
            }
            catch (Exception ex)
            {
                this.JSAlert("邮件发送失败!\n" + ex.Message);
            }

            this.EnablePage(true);
        }
        private void EnablePage(bool enabled)
        {
            this.btn_filter_enterprise.Enabled = enabled;
            this.btn_Send.Enabled = enabled;
        }
    }
}